package com.hangzhou.xyj.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.DianDramaDao;
import com.hangzhou.xyj.event.AnimationEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.DianDramaModel;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.type.EFileType;
import com.hangzhou.xyj.model.type.EPlayControlType;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.VerticalSeekBar;
import com.hangzhou.xyj.ui.widget.views.MyImageView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.DensityUtil;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.Utils;
import com.hangzhou.xyj.utils.constants.AppConstants;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.mediaideas.videoengine.AudioMixerParams;
import com.mediaideas.videoengine.AudioProc;
import com.mediaideas.videoengine.IAudioMixerService;
import com.mediaideas.videoengine.IAudioMixerStatusCallback;
import com.mediaideas.videoengine.lyrics.LrcView;
import com.mediaideas.videoengine.recorder.ApiHelper;
import com.mediaideas.videoengine.recorder.AudioRecorder;
import com.mediaideas.videoengine.recorder.AudioRecorderBuilder;
import com.mediaideas.videoengine.utils.FileUtils;
import com.mediaideas.videoengine.utils.MusicUtils;
import com.mediaideas.videoengine.utils.VideoEngineException;
import com.mediaideas.videoengine.utils.VideoEngineUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/1/26.
 */
public class RecordActivity extends BasePlayActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener,
        BasePlayActivity.OnMediaPlayerCompleteListener, BasePlayActivity.OnServiceConnectedListener {
    private final static String TAG = "RecordActivity";
    // 混音AIDL回调
    protected IAudioMixerStatusCallback mAudioMixerCallback = new IAudioMixerStatusCallback.Stub() {
        @Override
        public void onStartAudioMixer() throws RemoteException {

        }

        @Override
        public void onAudioMixerProgress(int progress) throws RemoteException {

            sendHandlerMessage(MSG_SHOW_MIXER_PROGRESS_VIEW, null, progress, -1);
        }

        @Override
        public void onFinishedAudioMixer(int result, String path) throws RemoteException {
            sendHandlerMessage(MSG_SHOW_MIXER_PROGRESS_VIEW, path, 100, result);
        }
    };
    protected DianDramaModel mDramaModel; //戏曲
    private ImageButton mBtnBack;//返回按钮
    private MyTextView mTvSingName;
    private MyTextView mBtnNoLyric;
    private MyTextView mBtnUseNative;
    private MyTextView mBtnRadioLevel;
    private MyTextView mBtnRetrySing;
    private MyTextView mBtnTimerHint;
    private MyImageView mBtnStartRecorder;
    private MyTextView mBtnEndRecord;
    private MyTextView mBtnCancelMixer;
    private float mAccompanyVolume = 1.0F; //伴奏音量
    private float mShakeLightVolume = 1.0F; //
    private String mRecordFilePath; //录音文件路径
    private String mAccompanyPath;//伴奏路径
    private String mNativePath;//原唱路径
    private boolean isPause = false;//是否暂停
    private boolean isRecord;//是否记录

    private AudioRecorder mAudioRecorder;
    private Timer mTimerSing;
    private TimerTask mTimerTaskSing;
    private IAudioMixerService mAudioMixerService;
    // 混音Service链接回调
    protected ServiceConnection audioMxierServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            LogUtil.d(TAG, "mxier Service connected");
            try {
                mAudioMixerService = IAudioMixerService.Stub.asInterface(iBinder);
                mAudioMixerService.setAudioMixerStatusCallback(mAudioMixerCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            LogUtil.d(TAG, "mxier Service disconnected");
        }
    };

    @Override
    public void initIntentData(Intent intent) {
        mDramaModel = (DianDramaModel) intent.getSerializableExtra(DataKey.DRAMA);
        isRecord = intent.getBooleanExtra(DataKey.IS_RECORD, false);
        Log.d("debug", "进入的时候 伴奏地址：" + mDramaModel.getAccompanyUrl());
    }

    @Override
    public void onServiceConnected() {
        if (AppConstants.CURRENT_PLAY_STATE == EPlayControlType.PLAY) {
            AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PAUSE;
            EventBusUtil.postEvent(new AnimationEvent(false));//左上角动画 启动
            try {
                mService.stop();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void initDatas() {
        //设置标题
        if (StringUtil.isNotEmpty(mDramaModel.getName())) {
            mTvSingName.setText(mDramaModel.getName());
        }
        mHandler = new MsgHandler(this);
        final XYJApplication application = XYJApplication.getApplication(this);
        mAudioRecorder = application.getRecorder();
        //build录音类
        if (mAudioRecorder == null || mAudioRecorder.getStatus() == AudioRecorder.Status.STATUS_UNKNOWN) {
            mAudioRecorder = AudioRecorderBuilder.with(application)
                    .fileName(FileUtils.getNextSoundFileName(this))
                    .config(AudioRecorder.MediaRecorderConfig.DEFAULT)
                    .loggable()
                    .build();
            application.setRecorder(mAudioRecorder);
        }
        mAccompanyPath = PublicUtil.getFilePath(mDramaModel.getAccompanyUrl(), EFileType.AUDIO);
        mNativePath = PublicUtil.getFilePath(mDramaModel.getNativeUrl(), EFileType.AUDIO);
        initPlayBack(mAccompanyPath);
//        setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_record);
    }

    @Override
    public void initListeners() {
        mBtnBack.setOnClickListener(this);
        mBtnNoLyric.setOnClickListener(this);
        mBtnRadioLevel.setOnClickListener(this);
        mBtnStartRecorder.setOnClickListener(this);
        mBtnUseNative.setOnClickListener(this);
        mBtnEndRecord.setOnClickListener(this);
        mBtnRetrySing.setOnClickListener(this);
        mBtnCancelMixer.setOnClickListener(this);
        setOnMediaPlayerCompleteListener(this);
        setOnServiceConnectedListener(this);
    }

    @Override
    public void onMediaPlayerComplete() {//播放完成
//        stopPlayback();//停止播放
        stopAudioRecorderAndMixerAudio();//停止录制并 进行混音
    }

    @Override
    public void initTop() {
        enableTop(false);
        //设置媒体音量模式
        //see:http://www.2cto.com/kf/201503/386524.html
        //see:http://www.cnblogs.com/maxinliang/archive/2013/07/02/3167212.html
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }

    @Override
    public void initViews() {
        mLrcView = (LrcView) findViewById(R.id.lrc_view);
        mProgressBar = findView(R.id.audio_progress_bar);
        mBtnBack = findView(R.id.btn_back);
        mCurrentTime = (MyTextView) findViewById(R.id.current_play_time);
        mAudioDuration = (MyTextView) findViewById(R.id.audio_duration);
        mTvSingName = (MyTextView) findViewById(R.id.sing_name_hint);
        mBtnNoLyric = (MyTextView) findViewById(R.id.no_lyric_tv);
        mBtnUseNative = (MyTextView) findViewById(R.id.btn_use_native_mode);
        mBtnRadioLevel = (MyTextView) findViewById(R.id.tv_correct_radio_level);
        mBtnStartRecorder = (MyImageView) findViewById(R.id.btn_start_record);
        mBtnRetrySing = (MyTextView) findViewById(R.id.btn_retry_sing);
        mBtnTimerHint = (MyTextView) findViewById(R.id.timer_sing_tv);
        mBtnEndRecord = (MyTextView) findViewById(R.id.btn_end_record);
        mBtnCancelMixer = (MyTextView) findViewById(R.id.btn_cancel_mixer);
        ViewGroup.LayoutParams layoutParams = mLrcView.getLayoutParams();
        layoutParams.height = Utils.getScreenWidth(this);
        mLrcView.setLayoutParams(layoutParams);

//        //初始化各个按钮的处理
        setNativeBtnEnable(false);//原唱按钮
        setRetryBtnEnable(false);//重唱按钮
        setEndRecordBtnEnable(false);//结束按钮
    }

    /**
     * 原唱按钮
     *
     * @param enable
     */
    private void setNativeBtnEnable(boolean enable) {
        mBtnUseNative.setEnabled(enable);
//        mBtnUseNative.setTextColor(enable ? getResources().getColor(R.color.common_white) : Color.parseColor("#666666"));
    }

    /**
     * 重唱按钮
     *
     * @param enable
     */
    private void setRetryBtnEnable(boolean enable) {
        mBtnRetrySing.setEnabled(enable);
//        mBtnRetrySing.setTextColor(enable ? getResources().getColor(R.color.common_white) : Color.parseColor("#666666"));
    }

    /**
     * 结束按钮
     *
     * @param enable
     */
    private void setEndRecordBtnEnable(boolean enable) {
        mBtnEndRecord.setEnabled(enable);
//        mBtnEndRecord.setTextColor(enable ? getResources().getColor(R.color.common_white) : Color.parseColor("#666666"));
    }

    /**
     * 设置录制按钮状态
     *
     * @param status
     */
    protected void setAudioRecorderBtnStatus(AudioRecorder.Status status) {
        if (status == AudioRecorder.Status.STATUS_UNKNOWN) { //未知状态
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_start);
        } else if (status == AudioRecorder.Status.STATUS_READY_TO_RECORD) { //准备录制
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_start);
        } else if (status == AudioRecorder.Status.STATUS_RECORDING) { //正在录音
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_pause);
        } else if (status == AudioRecorder.Status.STATUS_RECORD_PAUSED) { //暂停录制
            mBtnStartRecorder.setImageResource(R.drawable.ic_record_start);
        }
    }


    /**
     * 界面显示保存为已点戏曲, 并下载所需要的资源
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (isRecord) {
            saveAsDianDrama();
        }
        downloadInfos(); //下载有关戏曲的东西
        //发送一个统计的播放的请求
        //开始播放，请求一个统计播放量的接口
        UserModel info = XYJApplication.getUserInfo();
        if (info == null) {
            sendListeneReq(mDramaModel.getId(), -1);
        } else {
            long userId = -1;
            try {
                userId = Long.valueOf(info.getUserId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            sendListeneReq(mDramaModel.getId(), userId);
        }
    }

    /**
     * 下载有关音频的东西
     */
    private void downloadInfos() {
        //用父类下载原唱
        if (mDramaModel != null) {
            downloadNative(mDramaModel.getNativeUrl());
        }

        //下载伴唱
        if (mDramaModel != null) {
            downloadAccompany(mDramaModel.getAccompanyUrl());
        }

        //下载歌词
        if (mDramaModel != null) {
            downloadLyric(mDramaModel.getLrcUrl());
        }
    }

    /**
     * 保存为已点戏曲
     */
    private void saveAsDianDrama() {
        DianDramaDao dao = new DianDramaDao(mContext);
        //标记userId为自己的
        mDramaModel.setUserId(XYJApplication.getUserInfo().getUserId());
        //去重复，获取本地数据库，如果没有则保存为已点戏曲
        DianDramaModel drama = dao.getDrama(mDramaModel.getId());
        if (drama == null) {
            dao.addDrama(mDramaModel);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 绑定混音Service
        VideoEngineUtils.bindToAudioMixerService(this, audioMxierServiceConnection);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁定时任务
        if (mTimerTaskSing != null) {
            mTimerTaskSing.cancel();
        }
        if (mTimerSing != null) {
            mTimerSing.cancel();
        }
        //销毁播放资源
        try {
            if (mService != null && mService.isPlaying()) {
                mService.stop();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        // 销毁录音资源
        if (mAudioRecorder != null && mAudioRecorder.isRecording()) {
            mAudioRecorder.cancel();
            setResult(Activity.RESULT_CANCELED);
        }
        // 销毁混音资源
        destroyAudioMixer();
        // 解绑混音Service
        VideoEngineUtils.unbindFromeAudioMixerService(this, audioMxierServiceConnection);
    }

    /**
     * 音量控制PopupWindow
     *
     * @param view
     */
    protected void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.layout_correct_radio_level, null);
        VerticalSeekBar accompanySeekBar = (VerticalSeekBar) contentView.findViewById(R.id.accompany_volume_seekBar);
        VerticalSeekBar shakeLightSeekBar = (VerticalSeekBar) contentView.findViewById(R.id.shakelight_volume_seekBar);
        accompanySeekBar.setProgress((int) (mAccompanyVolume * 100));
        shakeLightSeekBar.setProgress((int) (mShakeLightVolume * 100));
        accompanySeekBar.setOnSeekBarChangeListener(this);
        shakeLightSeekBar.setOnSeekBarChangeListener(this);
        PopupWindow popup = new PopupWindow(contentView, DensityUtil.dip2px(this, 86), DensityUtil.dip2px(this, 185));
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        //点击popupWindow以外消失
        popup.setTouchable(true);
        popup.setFocusable(true);
        popup.setBackgroundDrawable(new BitmapDrawable());
        popup.showAtLocation(view, Gravity.NO_GRAVITY, location[0] - DensityUtil.dip2px(this, 6), location[1] - popup.getHeight() - DensityUtil.dip2px(this, 6));
        mBtnRadioLevel.setTextColor(Color.parseColor("#440303"));
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mBtnRadioLevel.setTextColor(Color.WHITE);
            }
        });
    }

    /**
     * 拖动SeekBar音量回调
     *
     * @param seekBar
     * @param progress
     * @param fromUser
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // 伴奏调音0-1.0F
        if (seekBar.getId() == R.id.accompany_volume_seekBar/* && fromUser*/) {
            setVolume(progress / 100.0F);
            mAccompanyVolume = progress / 100.0F;
            LogUtil.e(TAG, "mAccompanyVolume=" + mAccompanyVolume);
        } else if (seekBar.getId() == R.id.shakelight_volume_seekBar/* && fromUser*/) {
            // 原唱调音0-1.0F
            mShakeLightVolume = progress / 100.0F;
            LogUtil.e(TAG, "mShakeLightVolume=" + mShakeLightVolume);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if (seekBar.getId() == R.id.accompany_volume_seekBar) {

        } else if (seekBar.getId() == R.id.shakelight_volume_seekBar) {

        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (seekBar.getId() == R.id.accompany_volume_seekBar) {

        } else if (seekBar.getId() == R.id.shakelight_volume_seekBar) {

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putFloat("mAccompanyVolume", mAccompanyVolume);
        outState.putFloat("mShakeLightVolume", mShakeLightVolume);
        outState.putString("mRecordFilePath", mRecordFilePath);
    }

    //    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case REQUEST_CODE_PERMISSIONS:
//                boolean userAllowed = true;
//                for (final int result : grantResults) {
//                    userAllowed &= result == PackageManager.PERMISSION_GRANTED;
//                }
//                if (userAllowed) {
//                    startAudioRecorder(false);
//                } else {
//                    /*
//                     * Cannot show dialog from here
//                     * https://code.google.com/p/android-developer-preview/issues/detail?id=2823
//                     */
//                    showNeedPermissionsMessage();
//                }
//                break;
//            default:
//                break;
//        }
//    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mAccompanyVolume = savedInstanceState.getFloat("mAccompanyVolume", 1.0F);
        mShakeLightVolume = savedInstanceState.getFloat("mShakeLightVolume", 1.0F);
        mRecordFilePath = savedInstanceState.getString("mRecordFilePath", null);
    }

    private void showNeedPermissionsMessage() {
        setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
        ToastUtil.show(getString(R.string.error_no_permissions));
    }

    //    /**
//     * 开始录制
//     */
    protected void tryStartAudioRecorder() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            final int checkAudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
//            final int checkStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            if (checkAudio != PackageManager.PERMISSION_GRANTED || checkStorage != PackageManager.PERMISSION_GRANTED) {
//                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
//                    showNeedPermissionsMessage();
//                } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                    showNeedPermissionsMessage();
//                } else {
//                    ActivityCompat.requestPermissions(this, new String[]{
//                                    Manifest.permission.RECORD_AUDIO,
//                                    Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                            REQUEST_CODE_PERMISSIONS);
//                }
//            } else {
//                startAudioRecorder(false);
//            }
//        } else {
        startAudioRecorder();
//        }
    }

    /**
     * 开始录制
     */
    protected void startAudioRecorder() {
        //开启录音
        mAudioRecorder.start(new AudioRecorder.OnStartListener() {
            @Override
            public void onStarted() {
                Log.d(TAG, "开启录制");
                //mAudioRecorder.getStatus()：AudioRecorder.Status.STATUS_RECORDING
                //开始录音：置原唱按钮为伴奏，重唱按钮启用，结束按钮启用
                setNativeBtnEnable(true);
                setRetryBtnEnable(true);
                setEndRecordBtnEnable(true);
                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
//                if (!retry) {
//                    //开启伴奏
//                    startPlayback(PublicUtil.getFilePath(mDramaModel.getAccompanyUrl(), EFileType.AUDIO));
//                }
            }

            @Override
            public void onException(Exception e) {
                setResult(Activity.RESULT_CANCELED);
//                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
                ToastUtil.show(getString(R.string.error_audio_recorder, e));
            }
        });
    }

    // 停止录制 并且进行混音
    protected void stopAudioRecorderAndMixerAudio() {
        if (isAudioRecording()) {
            mAudioRecorder.stop(new AudioRecorder.OnStopListener() {
                @Override
                public void onStop(String activeRecordFileName) {
                    mRecordFilePath = activeRecordFileName;
                    startMixerAudio();//开始混音
                }

                @Override
                public void onException(Exception e) {

                }
            });
        }
    }


    /**
     * 停止录音 并删除录音文件
     */
    private void stopAudioRecorder() {
        if (isAudioRecording()) {
            mAudioRecorder.stop(new AudioRecorder.OnStopListener() {
                @Override
                public void onStop(String activeRecordFileName) {
                    FileUtils.deleteFile(activeRecordFileName);
//                    FileUtils.deleteFile(mAudioRecorder.getRecordFileName());
                }

                @Override
                public void onException(Exception e) {

                }
            });
        }
    }


    // 暂停录制
    protected void pauseAudioRecorder() {
        mAudioRecorder.pause(new AudioRecorder.OnPauseListener() {
            @Override
            public void onPaused(String activeRecordFileName) {
                mRecordFilePath = activeRecordFileName;
                setResult(Activity.RESULT_OK,
                        //new Intent().setData(Uri.parse(mRecordFilePath)));
                        new Intent().setData(ApiHelper.saveAudioFileToMediaLibrary(RecordActivity.this, mRecordFilePath)));
                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
                pausePlayback();
            }

            @Override
            public void onException(Exception e) {
                setResult(Activity.RESULT_CANCELED);
                setAudioRecorderBtnStatus(mAudioRecorder.getStatus());
                ToastUtil.show(getString(R.string.error_audio_recorder, e));
                pausePlayback();
            }
        });
    }

    // 播放录音文件
    protected void playAudioRecorder() {
        if (FileUtils.isFileExists(mRecordFilePath)) {
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(FileUtils.filePathToUri(mRecordFilePath), "audio/*");
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_correct_radio_level: //调节音量
                showPopupWindow(v);
                break;
            case R.id.btn_back: //返回按钮
                showGiveupRecorderDlg();
                break;
//            case R.id.no_lyric_tv: //调试按钮
//                playAudioRecorder();
//                break;
            case R.id.btn_use_native_mode: //原唱伴奏切换
                if (!isAudioRecording()) {
                    return;
                }

                //当前播放的url为空，则播放伴奏
                if (StringUtil.isBlank(mCurrentPlayFilePath)) {
                    startPlayback(mAccompanyPath);
                    return;
                }

                String audioFilePath = null;
                //当前播放为原唱，切换为伴奏
                if (mCurrentPlayFilePath.equals(mNativePath)) {
                    audioFilePath = mAccompanyPath;
                    if (!FileUtils.isFileExists(audioFilePath)) {
                        //文件不存在,不操作
                        ToastUtil.show("未找到原唱");
                        return;
                    }
                    mBtnUseNative.setText("原唱");
                }

                //当前播放为伴唱，切换为原唱
                if (mCurrentPlayFilePath.equals(mAccompanyPath)) {

                    audioFilePath = mNativePath;
                    if (!FileUtils.isFileExists(audioFilePath)) {
                        //文件不存在,不操作
                        ToastUtil.show("未找到伴唱");
                        return;
                    }
                    mBtnUseNative.setText("伴唱");
                }

                //播放问的路径为空
                if (StringUtil.isBlank(audioFilePath)) {
                    return;
                }

                //切换到目标文件播放
                long position = getPrePlayPosition(audioFilePath);
                startPlayback(PublicUtil.getFilePath(audioFilePath, EFileType.AUDIO), position);
                break;
            case R.id.btn_start_record://开始/暂停 按钮
                if (isAudioRecording()) { //正在录音:弹出对话框是否终止录音
                    showMixerAudioDlg(); // 停止播放，停止录音 并 混音
                } else {
                    startPlayWithTimeCount();
//                    startPlayback(PublicUtil.getFilePath(mDramaModel.getAccompanyUrl(), EFileType.AUDIO)); //开启播放
//                    tryStartAudioRecorder(); //开启录制
                }
                break;
            case R.id.btn_retry_sing: //重唱
                showReRecordingDlg();
                break;
            case R.id.btn_end_record: //结束
                showMixerAudioDlg(); //停止播放，停止录音 并 混音
                break;
            case R.id.btn_cancel_mixer: //取消混音
                cancelMixerAudio();
                hideMixerProgressView();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showGiveupRecorderDlg();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 跳转到预览界面
     *
     * @param mixerFilePath
     */
    protected void showPreviewRecordPage(String mixerFilePath) {
        RecordModel record = new RecordModel();
        record.setId(mDramaModel.getId());
        record.setName(mDramaModel.getName());
        record.setNativeUrl(mDramaModel.getNativeUrl());
        record.setAccompanyUrl(mDramaModel.getAccompanyUrl());
        Log.d("debug", "伴奏地址" + mDramaModel.getAccompanyUrl());
        record.setLrcUrl(mDramaModel.getLrcUrl());
        record.setDuration(mDuration / 1000);
        record.setUserId(XYJApplication.getUserInfo().getUserId()); //设置用户id
        record.setMixerFilePath(mixerFilePath); //录音文件只有本地混音路径，其他都为空
        record.setCreateTime(System.currentTimeMillis());//设置戏曲创建时间
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(mixerFilePath);
            mediaPlayer.prepare();
            record.setDuration(mediaPlayer.getDuration());//设置录音时长
            mediaPlayer.release();
        } catch (Exception e) {
            e.printStackTrace();
        }

        IntentManager.getInstance().goPreviewRecordActivity(mContext, record);
    }

    // 启动进度条刷新
    @Override
    protected long startRefreshProgressHint() {
        if (mService == null) {
            return 500;
        }
        try {
            long position = mService.position();
            if (position >= 0 && mDuration > 0) {
                mCurrentTime.setText(MusicUtils.makeTimeString(this, position / 1000));
                int progress = (int) (1000 * position / mDuration);
                mProgressBar.setProgress(progress);
//                if (mService.isPlaying()) {
//                    Utils.showAndDismissView(mProgressBar, true);
//                    Utils.showAndDismissView(mAudioDuration, true);
//                    Utils.showAndDismissView(mCurrentTime, true);
//                } else {
//                    // blink the counter
//                    int visibility = mCurrentTime.getVisibility();
//                    boolean isShow = visibility == View.INVISIBLE ? true : false;
//                    Utils.showAndDismissView(mCurrentTime, isShow);
//                    return 500;
//                }
            } /*else {
                mCurrentTime.setText("__:__");
                mProgressBar.setProgress(1000);
            }*/
            // calculate the number of milliseconds until the next full second, so
            // the counter can be updated at just the right time
            long remaining = 1000 - (position % 1000);

            // approximate how often we would need to refresh the slider to
            // move it smoothly
            int width = mProgressBar.getWidth();
            if (width == 0) width = 320;
            long smoothrefreshtime = mDuration / width;

            if (smoothrefreshtime > remaining) return remaining;
            if (smoothrefreshtime < 20) return 20;
            return smoothrefreshtime;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 500;
    }

    /**
     * 是否正在录制
     *
     * @return
     */
    protected boolean isAudioRecording() {
        return mAudioRecorder != null &&
                mAudioRecorder.getStatus() == AudioRecorder.Status.STATUS_RECORDING;
    }

    /**
     * 是否录制暂停
     *
     * @return
     */
    protected boolean hasAudioRecorded() {
        return mAudioRecorder != null &&
                mAudioRecorder.getStatus() == AudioRecorder.Status.STATUS_RECORD_PAUSED;
    }

    /**
     * 弹出是否退出录制界面Dialog
     */
    protected void showQuitRecordPageDlg() {

        new AlertDialog.Builder(this)
                .setTitle(R.string.service_start_error_title)
                .setMessage(R.string.service_start_error_msg)
                .setPositiveButton(R.string.service_start_error_button,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                finish();
                            }
                        })
                .setCancelable(false)
                .show();
    }

    /**
     * 弹出 退出 对话框
     */
    protected void showGiveupRecorderDlg() {
        if (isAudioRecording()) {//如果正在录制
            TipsDialog dialog = new TipsDialog(mContext, "提示", "当前歌曲正在录制，退出前是否保存？",
                    "保存", "不保存") {
                @Override
                protected void OnClickNegativeButton() {
                    stopPlayback();//停止播放()
                    stopAudioRecorder();//停止录音 并 删除
                    this.dismiss();
                    closeActivity();
                }

                @Override
                protected boolean OnClickPositiveButton() {
                    //保存
                    stopPlayback();//停止播放
                    stopAudioRecorderAndMixerAudio();//停止录音 并 混音
                    //设置中间按钮图片
                    setAudioRecorderBtnStatus(AudioRecorder.Status.STATUS_RECORD_PAUSED);
//                    closeActivity();
                    return true;
                }

            };
            dialog.setCancel(true);
            dialog.show();
        } else {//没有启动录制
            new TipsDialog(mContext, "提示", "录音还没有开始，确定要退出吗？",
                    "确定", "取消") {
                @Override
                protected void OnClickNegativeButton() {
                    this.dismiss();
                }

                @Override
                protected boolean OnClickPositiveButton() {
//                    pauseAudioRecorder();
//                    stopAudioRecorder();//停止录音
//                    pausePlayback();//暂停播放
                    FileUtils.deleteFile(mRecordFilePath);//删除录音文件
                    this.dismiss();
                    closeActivity();
                    return true;
                }
            }.show();
        }
    }

    /**
     * 弹出 重新录制 对话框
     */
    protected void showReRecordingDlg() {
        // 启动过录音并且没有做过混音操作,直接跳出
        if (!isAudioRecording()) {
            return;
        }
//        Utils.setTextColor(mBtnRetrySing, true);
        new TipsDialog(mContext, "提示", "当前歌曲还没有结束，确定要重新录制吗？",
                "确定", "取消") {
            @Override
            protected void OnClickNegativeButton() {
//                sendHandlerMessage(MSG_UPDATE_BTN_COLOR, null, mBtnRetrySing.getId(), -1);
                this.dismiss();
            }

            @Override
            protected boolean OnClickPositiveButton() {
                startPlayWithTimeCount();
                this.dismiss();
                return true;
            }
        }.show();
    }

    /**
     * 倒计时 并开始播放
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/19 17:28
     */
    private void startPlayWithTimeCount() {
        mBtnStartRecorder.setEnabled(false);//开启录音  不可以点击
        if (isAudioRecording()) {//如果在录制
            stopAudioRecorder();//停止录音
            pausePlayback();//暂停播放
            isPause = true;
            setAudioRecorderBtnStatus(AudioRecorder.Status.STATUS_RECORD_PAUSED);
        }
        mTimerSing = new Timer();
        mTimerTaskSing = new TimerTask() {//启动倒计时
            int progress = 3;

            @Override
            public void run() {
                if (progress < 0) {//倒数到小于0了
                    mTimerSing.cancel();
                    mTimerTaskSing.cancel();
                    sendHandlerMessage(MSG_BTN_TIMER_HINT_TEXT, String.valueOf(3), 0, -1);//重置为4 并且不显示
//                    setAudioRecorderBtnStatus(AudioRecorder.Status.STATUS_RECORDING);
//                            sendHandlerMessage(MSG_BTN_TIMER_HINT_SHOW, null, 0, -1);
//                            sendHandlerMessage(MSG_UPDATE_BTN_COLOR, null, R.id.btn_retry_sing, -1);
                    try {
                        if (!isPause || mNativePath.equals(mCurrentPlayFilePath)) {//如果是第一次启动 或者点击重唱的时候 是播放的原唱
                            sendHandlerMessage(MSG_TIME_COUNT_DONE, null, -1, -1);//重启播放 播放伴奏
                        } else {
                            mService.seek(0);//回到起始点
                            mService.play();//开始播放
                        }
                        startLrcPlay();//开始歌词
                        startAudioRecorder();//开启录音
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                if (progress == 0) {// 3 2 1 Go!
                    sendHandlerMessage(MSG_BTN_TIMER_HINT_TEXT, "GO!", 1, -1);
                    progress--;
                    return;
                }
                sendHandlerMessage(MSG_BTN_TIMER_HINT_TEXT, String.valueOf(progress--), 1, -1);
            }
        };
//                Utils.setTextColor(mBtnRetrySing, true);
        mTimerSing.schedule(mTimerTaskSing, 0, 1000);
    }

    /**
     * 弹出混音对话框  操作：停止播放，停止录音 并 混音
     */
    protected void showMixerAudioDlg() {
        new TipsDialog(mContext, "提示", "当前歌曲还没有结束，确定要完成录制吗？",
                "确定", "取消") {
            @Override
            protected void OnClickNegativeButton() {
                this.dismiss();
            }

            @Override
            protected boolean OnClickPositiveButton() {
                stopPlayback();//停止播放
                stopAudioRecorderAndMixerAudio();//停止录音 并 混音
                //设置中间按钮图片
                setAudioRecorderBtnStatus(AudioRecorder.Status.STATUS_RECORD_PAUSED);
                this.dismiss();
                return true;
            }
        }.show();
    }

    // 显示混音进度对话框
    protected void showMixerProgressView(int progress, int result) {
        View view = findViewById(R.id.audio_mixer_view);
        if (view != null && progress >= 0 && result != 1 && hasAudioMixerProcessing()) {
            Utils.showAndDismissView(view, true);
            TextView mixerHintTV = (TextView) view.findViewById(R.id.mixer_progress_hint);
            mixerHintTV.setText("正在合成... " + progress + "%");
            ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.audio_mixer_progress_bar);
            progressBar.setProgress(progress);
        } else {
            Utils.showAndDismissView(view, false);
        }
    }

    // 隐藏混音进度对话框
    protected void hideMixerProgressView() {
        View view = findViewById(R.id.audio_mixer_view);
        Utils.showAndDismissView(view, false);
    }

    // 开始混音
    protected void startMixerAudio() {
        if (!FileUtils.isFileExists(mRecordFilePath)) {
            ToastUtil.show("录音文件不存在");
            return;
        }
        //伴奏文件路径
        String accompanyFilePath = PublicUtil.getFilePath(mDramaModel.getAccompanyUrl(), EFileType.AUDIO);
        if (!FileUtils.isFileExists(accompanyFilePath)) {
            ToastUtil.show("伴唱文件不存在");
            return;
        }
        LogUtil.d(TAG, "开始混音...");

        File dstFile = FileUtils.getAudioFile(this, System.currentTimeMillis() + "");
        try {
            if (mAudioMixerService != null && dstFile != null) {
                stopLrcPlay();
                final AudioMixerParams audioMixerParams = new AudioMixerParams();
                audioMixerParams.setSrcAudioFilePath(mRecordFilePath);
                audioMixerParams.setBackgroundAudioFilePath(accompanyFilePath);
                audioMixerParams.setDstAudioFilePath(dstFile.getAbsolutePath());
                audioMixerParams.setSrcAudioStartTime(1);
                audioMixerParams.setSrcAudioVolume(Math.min(mShakeLightVolume, 1.0F));
                audioMixerParams.setBackgroundAudioVolume(Math.min(mAccompanyVolume, 1.0F));
                audioMixerParams.setDstAudioSampleRate(AudioMixerParams.DEFAULT_SAMPLE_RATE);
                audioMixerParams.setDstAudioBitRate(AudioMixerParams.DEFAULT_BIT_RATE);
                long duration = Math.min(VideoEngineUtils.getMediaDuration(mRecordFilePath), mDuration);
                audioMixerParams.setAudioMixerDuration(duration);
                mAudioMixerService.startAudioMixer(audioMixerParams);
            }
        } catch (VideoEngineException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    // 取消混音
    protected void cancelMixerAudio() {
        try {
            if (hasAudioMixerProcessing()) {
//                startLrcPlay();
                this.finish();//关闭本窗口
                mAudioMixerService.cancelAudioMixer();
                int servicePid = mAudioMixerService.getAudioMixerServicePid();
                Log.e(TAG, "KillAudioMixerService Pid=" + servicePid);
                try {
                    if (servicePid > 0) {
                        Log.e(TAG, "Main Process Pid=" + android.os.Process.myPid());
//                        VideoEngineUtils.unbindFromeAudioMixerService(this, audioMxierServiceConnection);
//                        android.os.Process.killProcess(servicePid);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    // 销毁混音
    protected int destroyAudioMixer() {
        try {
            if (mAudioMixerService != null) {
                return mAudioMixerService.destory();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return -1;
    }

    protected boolean hasAudioMixerProcessing() {
        try {
            if (mAudioMixerService != null
                    && mAudioMixerService.getAudioProcessStatus() == AudioProc.STATUS_AUDIO_PROC_SAVING) {
                return true;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return false;
    }

    protected class MsgHandler extends Handler {
        protected WeakReference<RecordActivity> reference;

        public MsgHandler(RecordActivity activity) {
            reference = new WeakReference<RecordActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            RecordActivity activity = reference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case MSG_BTN_TIMER_HINT_SHOW:
                    boolean isShow = msg.arg1 == 1;
                    Utils.showAndDismissView(activity.mBtnTimerHint, isShow);
                    break;
                case MSG_BTN_TIMER_HINT_TEXT:
                    if (String.valueOf(msg.obj).equals("GO!"))
                        mBtnStartRecorder.setEnabled(true);//开启录音  可以点击
                    activity.mBtnTimerHint.setText(String.valueOf(msg.obj));//
                    Utils.showAndDismissView(activity.mBtnTimerHint, msg.arg1 == 1);
                    break;
                case MSG_REFRESH_PROGRESS_POS:
                    long next = activity.startRefreshProgressHint();
                    activity.sendNextRefreshMessage(next);
                    break;
                case MSG_MEDIA_PLAY_QUIT: //退出录音Dialog
                    activity.showQuitRecordPageDlg();
                    break;
                case MSG_UPDATE_BTN_COLOR: //更新btn颜色
                    String path = String.valueOf(msg.obj);
                    if (TextUtils.equals(path, mDramaModel.getAccompanyUrl())) {
                        Utils.setTextColor(activity.mBtnEndRecord, true);
                        Utils.setTextColor(activity.mBtnUseNative, false);
                    } else if (TextUtils.equals(path, mDramaModel.getNativeUrl())) {
                        Utils.setTextColor(activity.mBtnEndRecord, false);
                        Utils.setTextColor(activity.mBtnUseNative, true);
                    } else if (TextUtils.equals(path, "null") && msg.arg1 == R.id.btn_retry_sing) {
                        Utils.setTextColor(activity.mBtnRetrySing, msg.arg2 > 0 ? true : false);
                    }
                    break;
                case MSG_SHOW_MIXER_PROGRESS_VIEW: //显示混音进度View
                    activity.showMixerProgressView(msg.arg1, msg.arg2);
                    if (msg.arg2 == AudioProc.STATUS_AUDIO_PROC_SUCCESS && msg.obj != null) {
                        closeActivity();
//                        ToastUtil.show("音频合成结束，保存在：" + String.valueOf(msg.obj));
                        activity.showPreviewRecordPage(String.valueOf(msg.obj));
                    }
                    break;
                case MSG_TIME_COUNT_DONE://倒计时完成
                    startPlayback(mAccompanyPath);//播放伴奏
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
